package com.copera.cn.kaka;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.copera.cn.kaka.picpopupwindow.SelectPicPopupWindow;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.util.JsonUtil;
import com.copera.cn.kaka.util.Options;
import com.copera.cn.kaka.util.UploadUtil;
import com.copera.cn.kaka.util.Utility;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ShopPhotoDelActivity extends BaseActivity {
	private ImageView shopphoto,bigphoto;
	// 自定义的弹出框类
	private SelectPicPopupWindow menuWindow;
	private String type;
	private RelativeLayout back;

	private EditText description;
	
  
   
	private Uri photoUri;
	
	private String id;
	private Button del,sav;
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	private Bitmap bp,loadBitmap;
	private int displayWidth;
	private String title;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.shop_photo_del);
		back = (RelativeLayout) findViewById(R.id.back);
		imageId=getIntent().getStringExtra("imageId");
		loadImage();
		hasDel=null;
		description = (EditText) findViewById(R.id.description);
		del = (Button) findViewById(R.id.del);
		sav = (Button) findViewById(R.id.sav);
		shopphoto = (ImageView) findViewById(R.id.photo);
		bigphoto = (ImageView) findViewById(R.id.bigphoto);
		fl =(FrameLayout)findViewById(R.id.fl);
		shopphoto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(ShopPhotoDelActivity.this,
						itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

			}
		});
		bigphoto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(ShopPhotoDelActivity.this,
						itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

			}
		});
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//recycle();
				finish();

			}
		});
		del.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				fl =(FrameLayout)findViewById(R.id.fl);
				fl.setVisibility(View.GONE);
				ImageView add =(ImageView)findViewById(R.id.photo);
				add.setVisibility(View.VISIBLE);
				Button save =(Button)findViewById(R.id.saveButton2);
				Button save1 =(Button)findViewById(R.id.saveButton1);
				save1.setVisibility(View.GONE);
				
				description.setText("");
				sav.setVisibility(View.GONE);
				save.setVisibility(View.VISIBLE);
				imageId=null;
				//loadBitmap.recycle();
				delImage();
			}
		});

		
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		displayWidth = dm.widthPixels;
		description.setFocusable(true);
		description.setFocusableInTouchMode(true);   
		description.requestFocus();
		//强制为竖屏 
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	private String shopImage,hasDel;
	private FrameLayout fl;
	public void doDel(View view){
		
		fl.setVisibility(View.GONE);
		ImageView add =(ImageView)findViewById(R.id.photo);
		add.setVisibility(View.VISIBLE);
		Button save =(Button)findViewById(R.id.saveButton2);
		Button save1 =(Button)findViewById(R.id.saveButton1);
		save.setVisibility(View.VISIBLE);
		save1.setVisibility(View.GONE);
		hasDel="1";
		final List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", getIntent().getStringExtra("imageId")));
		new Thread() {
			public void run() {
				
				try {
					String json = HttpUtils.post(ActionUrls.URL_DEL_SHOPIMAGE,params,getAppCustomer().getHttpClient());
					String message = JsonUtil.getMessage(json);
					if(message.equals("删除图片成功")){
						
					}
				} catch (Exception e) {
					
					e.printStackTrace();
				}

				
			}
		}.start();
	
	}
	private String imageId;
	//只编辑标题
	public void doSave(View view){
		final List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("describe", description.getText().toString()));
		params.add(new BasicNameValuePair("id", imageId));
		params.add(new BasicNameValuePair("name",shopImage));
		boolean bool = true;
		String descriptions =  description.getText().toString();
		if (descriptions == null || "".equals(descriptions)) {
			bool = false;
			Toast.makeText(ShopPhotoDelActivity.this, "请输入活动描述",Toast.LENGTH_SHORT).show();
		}else if (getAppCustomer().getPhotoFile() == null&&picPath==null&&hasDel!=null) {
			bool = false;
			Toast.makeText(ShopPhotoDelActivity.this, "请上传店铺活动宣传图片",Toast.LENGTH_SHORT).show();
		}else if (descriptions.length() > 25) {
			bool = false;
			Toast.makeText(ShopPhotoDelActivity.this, "您输入的活动描述字数超过25个字",Toast.LENGTH_SHORT).show();
		}
		if (bool) {
			if(photo!=null&&!photo.equals("")){
				if(photo.equals("1")){
					upload(bp);
				}else{
					upload();
				}
				hasDel=null;
				 Intent data=new Intent();  
				 data.putExtra("filename", file.getAbsolutePath()); 
				 setResult(120, data);  
				finish();
			}else{
				new Thread() {
					public void run() {
						
						try {
							String json = HttpUtils.post(ActionUrls.URL_EDIT_SHOPIMAGE, params,	getAppCustomer().getHttpClient());
							String message = JsonUtil.getMessage(json);
							if(message.equals("编辑成功")){
								finish();
							}
						} catch (Exception e) {
							
							e.printStackTrace();
						}

						
					}
				}.start();
			}
			
		}
		
	}
	
	
    public void loadImage(){

		new AsyncTask<String, Integer, String>(){

			@Override
			protected String doInBackground(String... params) {
				JSONObject jsonObj=null;
				try{
					String jsonStr=HttpUtils.get(params[0], getAppCustomer().getHttpClient());
					
					if(jsonStr!=null){
						jsonObj=new JSONObject(jsonStr);
						
						String headImage = jsonObj.getJSONObject("image").getString("fileName");
						shopImage=headImage;
						type=jsonObj.getJSONObject("image").getString("type");
						id=jsonObj.getJSONObject("image").getString("id");
						String des = jsonObj.getJSONObject("image").getString("description");
						title = des.equals("无")?"":des;
						
						return headImage;
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String headImage) {
				
				if(headImage!=null){
					try{
						imageLoader.displayImage(ActionUrls.HOST_IMG+headImage, bigphoto, Options.getListOptions());
						description.setText(title);
					}catch(Exception e){
						e.printStackTrace();
						if(e.getMessage() != null){
							
						}
					}
				}
			}
			
		}.execute(ActionUrls.URL_LOADIMAGE+"?imageId="+getIntent().getStringExtra("imageId"));
	
    }
   public void delImage(){

	   new AsyncTask<String, Integer, JSONObject>(){

			@Override
			protected JSONObject doInBackground(String... params) {
				JSONObject jsonObj=null;
				try{
					String jsonStr=HttpUtils.get(params[0], getAppCustomer().getHttpClient());
					
					if(jsonStr!=null){
						jsonObj=new JSONObject(jsonStr);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				return jsonObj;
			}

			@Override
			protected void onPostExecute(JSONObject result) {
				
				if(result!=null){
					try{
						String message = result.getString("message");
						if(message.equals("success")){
							bigphoto.setVisibility(View.GONE);
							bigphoto.setBackgroundDrawable(null);
							shopphoto.setVisibility(View.VISIBLE);
						}
						//sav.setVisibility(View.VISIBLE);
						del.setVisibility(View.GONE);
						
					}catch(Exception e){
						e.printStackTrace();
						if(e.getMessage() != null){
							
						}
					}
				}
			}
			
		}.execute(ActionUrls.URL_DELIMAGE+"?imageId="+getIntent().getStringExtra("imageId"));
	
   }
	// 为弹出窗口实现监听类
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();
			Intent intent = null;
			int id = v.getId();
			if (id == R.id.btn_take_photo) {
				
				intent = new Intent(ShopPhotoDelActivity.this,PhotoActivity.class);
				intent.putExtra("type", "banner");
				startActivityForResult(intent, 100);
				overridePendingTransition(R.layout.push_left_in, R.layout.push_left_out);
			} else if (id == R.id.btn_pick_photo) {
				intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
				getAppCustomer().setSelectType("zm");
			} else {
				//finish();
			}

		}
	};
	private String photo;
	ImageLoader imageLoader = ImageLoader.getInstance();
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		fl.setVisibility(View.VISIBLE);
		ImageView add =(ImageView)findViewById(R.id.photo);
		add.setVisibility(View.GONE);
		Button save =(Button)findViewById(R.id.saveButton2);
		Button save1 =(Button)findViewById(R.id.saveButton1);
		save.setVisibility(View.GONE);
		sav.setVisibility(View.GONE);
		save1.setVisibility(View.VISIBLE);
		ImageView del = (ImageView)findViewById(R.id.ico_del);
		del.setVisibility(View.GONE);
		 if (resultCode == 40) { 
			    photo="1";
			    imageLoader.displayImage("file://"+getAppCustomer().getPhotoFile(), bigphoto, Options.getListOptions());
			    bp = getAppCustomer().getGgimage();
				bigphoto.setVisibility(View.VISIBLE);
				shopphoto.setVisibility(View.GONE);
//			 upload(getAppCustomer().getGgimage());
		 }else if (resultCode == Activity.RESULT_OK) {
				doPhoto(requestCode, data);
				photo="2";
			}
		super.onActivityResult(requestCode, resultCode, data);
		
		
		
		
	}
	private File file;
	public void upload(Bitmap bitmap) {

		UploadUtil uploadUtil = UploadUtil.getInstance();
		file = null;

		try {
			
			try {
				file = UploadUtil.saveMyBitmap(bitmap);
				shopImage="/images/"+file.getName();
				long size = file.length() / 1024;

				System.out.println(size);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {

			e.printStackTrace();
		}
        getAppCustomer().setPhotoFile(null);
        photo=null;
        description.setFocusable(true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", imageId);
		params.put("shopId", getAppCustomer().getShop().getId());
		params.put("type", type);
		params.put("description", description.getText().toString());
		params.put("flag", "set");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);
		bitmap.recycle();
	}
	public void upload() {
        
		UploadUtil uploadUtil = UploadUtil.getInstance();
		 file = null;

		try {
			file = UploadUtil.saveFile(picPath);
			shopImage="/images/"+file.getName();
			long size = file.length() / 1024;

			System.out.println(size);
		} catch (Exception e) {

			e.printStackTrace();
		}
		description.setFocusable(true);
		photo=null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", imageId);
		params.put("shopId", getAppCustomer().getShop().getId());
		params.put("type", type);
		params.put("description", description.getText().toString());
		params.put("flag", "set");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);
	}
	private String picPath;
	private void doPhoto(int requestCode, Intent data) {
        if(data!=null){
        	if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
    		{
    			if (data == null) {
    				Toast.makeText(ShopPhotoDelActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
    				return;
    			}
    			photoUri = data.getData();
    			if (photoUri == null) {
    				Toast.makeText(ShopPhotoDelActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
    				return;
    			}
    		}
    		String[] pojo = { MediaStore.Images.Media.DATA };

    		//Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
    		ContentResolver cr = getContentResolver();
    		Cursor cursor=cr.query(photoUri, pojo, null, null, null);
    		if (cursor != null) {
    			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
    			cursor.moveToFirst();
    			picPath = cursor.getString(columnIndex);
    			cursor.close();
    		}

    		if (picPath != null
    				&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
    						|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG")|| picPath.endsWith(".jpeg")|| picPath.endsWith(".jpeg"))) {
    			BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(picPath, opts);
				File f = new File(picPath);
				if(f.length()/1024<100){
					opts.inSampleSize = 1;
				}else{
					opts.inSampleSize = Utility.getinSampleSize(opts);
				}
                opts.inJustDecodeBounds = false;
               
				
    			try {
    				imageLoader.displayImage("file://"+picPath, bigphoto, Options.getListOptions());
					
					bigphoto.setVisibility(View.VISIBLE);
					shopphoto.setVisibility(View.GONE);
    			} catch (Exception e) {
    				
    				e.printStackTrace();
    			}
    			

    		} else {
    			Toast.makeText(ShopPhotoDelActivity.this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
    		}
        }
		
	}
    
   

}
